package com.xnx3.kefu.site.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.j2ee.util.SystemUtil;
import com.xnx3.FileUtil;
import com.xnx3.j2ee.controller.BaseController;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.impl.SqlCacheServiceImpl;
import com.xnx3.kefu.core.entity.Kefu;
import com.xnx3.kefu.core.entity.KefuJS;
import com.xnx3.kefu.core.entity.Zuoxi;
import com.xnx3.kefu.core.util.KefuPropertiesUtil;

/**
 * 生成可以放到第三方网站的js
 * @author 管雷鸣
 */
@Controller(value="KefuSiteJSController")
@RequestMapping("/")
public class SiteKefuController extends BaseController {
	@Resource
	private SqlCacheService sqlCacheService;

	/**
	 * 获取当前客服的 kefuJS 信息
	 */
	@ResponseBody
	@RequestMapping("siteKefu.js")
	public String getKefuJS(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = false, defaultValue="") String id){
		if(id.length() < 1){
			return "kefu is null";
		}
		//读取坐席id对应的kefu
//		Kefu kefu = sqlCacheService.findAloneByProperty(Kefu.class, "userid", id);
		Zuoxi zuoxi = sqlCacheService.findById(Zuoxi.class, id);
		if(zuoxi == null){
			return "zuoxi not find";
		}
//		Kefu kefu = sqlCacheService.findById(Kefu.class, zuoxi.getKefuid());
//		if(kefu == null){
//			return "kefu bucunzai";
//		}
		//读取自定义js
		KefuJS kefuJS = sqlCacheService.findById(KefuJS.class, zuoxi.getKefuid());
		if(kefuJS == null){
			kefuJS = new KefuJS();
		}
		
		String path = SystemUtil.getClassesPath()+"static/js/yunkefu/siteKefu.js";
//		String path = "/Users/apple/git/yunkefu/src/main/resources/static/js/yunkefu/siteKefu.js";
		String str = FileUtil.read(path);
		str = str.replaceAll("\\{host\\}", KefuPropertiesUtil.getProperty("kefu.api"))
			.replaceAll("\\{socketUrl\\}", KefuPropertiesUtil.getProperty("kefu.socket"))
			.replaceAll("\\{zuoxiid\\}", zuoxi.getId())
			.replaceAll("\\{color\\}", kefuJS.getColor())
			.replaceAll("\\{backgroundColor\\}", kefuJS.getBackgroundColor());
		
		response.setContentType("text/javascript;charset=UTF-8");
		return str;
	}
	
}
